# -*- coding: utf-8 -*-
"""
PostGIS导入器测试脚本
测试Shapefile、GeoJSON和GeoPackage文件导入到PostGIS数据库
"""

import os
import sys
import sys
import os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..'))
from hydropulse.utils.postgis_importer import PostGISImporter
from loguru import logger

# 配置日志
logger.add(sys.stderr, format="{time} {level} {message}", level="INFO")

def test_import():
    """测试导入功能"""
    
    # 数据库连接配置
    # 请根据实际情况修改
    db_url = "postgresql://postgres:water@10.48.0.85:5432/hydro_pulse"
    
    # 创建导入器
    importer = PostGISImporter(db_url)
    
    # 测试文件列表
    test_files = [
        {
            'file_path': '碧流河.json',
            'description': 'GeoJSON测试文件'
        },
        {
            'file_path': 'gansu.gpkg',
            'description': 'GeoPackage测试文件'
        },
        {
            'file_path': '水库合并shp/shuiku.shp',
            'description': 'Shapefile测试文件'
        }
    ]
    
    results = []
    
    for test_file in test_files:
        file_path = test_file['file_path']
        description = test_file['description']
        
        if not os.path.exists(file_path):
            logger.warning(f"文件不存在: {file_path}")
            continue
            
        logger.info(f"开始导入 {description}: {file_path}")
        
        try:
            # 导入文件
            result = importer.import_file(file_path)
            results.append(result)
            
            if result['success']:
                logger.success(f"✅ {description} 导入成功")
                logger.info(f"   表名: {result['table_name']}")
                logger.info(f"   记录数: {result['record_count']}")
                logger.info(f"   几何类型: {result['geometry_type']}")
            else:
                logger.error(f"❌ {description} 导入失败: {result['error']}")
                
        except Exception as e:
            logger.error(f"❌ 导入过程中发生异常: {e}")
            results.append({
                'success': False,
                'error': str(e),
                'file_path': file_path
            })
    
    # 汇总结果
    logger.info("=== 导入结果汇总 ===")
    success_count = sum(1 for r in results if r.get('success', False))
    total_count = len(results)
    
    logger.info(f"成功: {success_count}/{total_count}")
    
    for result in results:
        status = "✅" if result.get('success') else "❌"
        logger.info(f"{status} {result['file_path']}: {result.get('error', '成功')}")
    
    return results

def test_table_info():
    """测试获取表信息"""
    
    db_url = "postgresql://postgres:water@10.48.0.85:5432/hydro_pulse"
    importer = PostGISImporter(db_url)
    
    tables = ['geometry_points', 'geometry_multipolygons']
    
    logger.info("=== 表信息 ===")
    for table in tables:
        try:
            info = importer.get_table_info(table)
            if 'error' in info:
                logger.error(f"❌ {table}: {info['error']}")
            else:
                logger.info(f"✅ {table}: {info['record_count']} 条记录, 类型: {info['geometry_type']}")
        except Exception as e:
            logger.error(f"❌ 获取 {table} 信息失败: {e}")

def test_clear_tables():
    """测试清空表数据功能"""
    
    db_url = "postgresql://postgres:water@10.48.0.85:5432/hydro_pulse"
    importer = PostGISImporter(db_url)
    
    tables = ['geometry_points', 'geometry_multipolygons']
    
    logger.info("=== 测试清空表数据 ===")
    
    # 清空前获取表信息
    logger.info("清空前的表信息:")
    for table in tables:
        try:
            info = importer.get_table_info(table)
            if 'error' not in info:
                logger.info(f"   {table}: {info['record_count']} 条记录")
        except Exception as e:
            logger.warning(f"   获取 {table} 信息失败: {e}")
    
    # 清空表数据
    try:
        result = importer.clear_tables(tables)
        if result['success']:
            logger.success(f"✅ 成功清空 {result['tables_processed']} 个表，共删除 {result['total_deleted']} 条记录")
            
            # 显示每个表的清空结果
            for table_result in result['results']:
                if table_result['success']:
                    logger.info(f"   {table_result['table_name']}: 删除 {table_result['deleted_count']} 条记录")
                else:
                    logger.error(f"   {table_result['table_name']}: 清空失败 - {table_result['error']}")
        else:
            logger.error(f"❌ 清空表数据失败")
            
    except Exception as e:
        logger.error(f"❌ 清空表数据时发生异常: {e}")
    
    # 清空后获取表信息
    logger.info("清空后的表信息:")
    for table in tables:
        try:
            info = importer.get_table_info(table)
            if 'error' not in info:
                logger.info(f"   {table}: {info['record_count']} 条记录")
        except Exception as e:
            logger.warning(f"   获取 {table} 信息失败: {e}")

if __name__ == "__main__":
    print("=== PostGIS导入器测试 ===")
    #清空表数据
    test_clear_tables()
    # 测试导入
    test_import()
    
    # 测试表信息
    test_table_info()
    
    print("\n=== 测试完成 ===")